from src.database.connection import HospitalDatabase
import tkinter.messagebox

# Initialize database connection
db = HospitalDatabase()
if not db.connect():
    print("Failed to connect to database")
    exit()

class AppointmentBackend:
    """Backend logic for appointment management"""
    
    def __init__(self):
        self.db = db
    
    def add_appointment(self, appointment_data):
        """Add a new appointment to the database"""
        try:
            return self.db.add_appointment(
                patient_id=appointment_data['patient_id'],
                staff_id=appointment_data['staff_id'],
                appointment_date=appointment_data['appointment_date'],
                appointment_time=appointment_data['appointment_time'],
                duration=appointment_data.get('duration', 30),
                notes=appointment_data.get('notes', '')
            )
        except Exception as e:
            raise Exception(f"Error adding appointment: {str(e)}")
    
    def update_appointment(self, appointment_id, update_data):
        """Update appointment information"""
        try:
            return self.db.update_appointment(appointment_id, **update_data)
        except Exception as e:
            raise Exception(f"Error updating appointment: {str(e)}")
    
    def delete_appointment(self, appointment_id):
        """Delete an appointment from the database"""
        try:
            return self.db.delete_appointment(appointment_id)
        except Exception as e:
            raise Exception(f"Error deleting appointment: {str(e)}")
    
    def get_appointment(self, appointment_id):
        """Get appointment by ID"""
        try:
            return self.db.get_appointment(appointment_id)
        except Exception as e:
            raise Exception(f"Error getting appointment: {str(e)}")
    
    def get_all_appointments(self):
        """Get all appointments from database"""
        try:
            return self.db.get_all_appointments()
        except Exception as e:
            raise Exception(f"Error getting all appointments: {str(e)}")
    
    def validate_appointment_data(self, appointment_data):
        """Validate appointment data before saving - relaxed restrictions"""
        required_fields = ['patient_id', 'staff_id', 'appointment_date', 'appointment_time']
        
        for field in required_fields:
            if not appointment_data.get(field):
                return False, f"Field '{field}' is required"
        
        # Validate patient_id is positive
        try:
            patient_id = int(appointment_data['patient_id'])
            if patient_id <= 0:
                return False, "Patient ID must be a positive number"
        except ValueError:
            return False, "Patient ID must be a valid number"
        
        # Validate duration if provided (relaxed: allow 0 or positive, just check if it's valid number)
        if appointment_data.get('duration') is not None:
            try:
                duration = int(appointment_data['duration'])
                if duration < 0:
                    return False, "Duration cannot be negative"
                # Allow 0 duration (relaxed restriction)
            except ValueError:
                return False, "Duration must be a valid number"
        
        return True, "Valid"

